using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Timing;
using System.Text.Json;

namespace CKY.AgentPlatform.Monitoring
{
    /// <summary>
    /// 日志级别枚举
    /// </summary>
    public enum LogLevel
    {
        Debug = 0,
        Information = 1,
        Warning = 2,
        Error = 3,
        Critical = 4
    }

    /// <summary>
    /// 日志条目
    /// </summary>
    public class LogEntry
    {
        /// <summary>
        /// 日志ID
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 时间戳
        /// </summary>
        public DateTime Timestamp { get; set; }

        /// <summary>
        /// 日志级别
        /// </summary>
        public LogLevel Level { get; set; }

        /// <summary>
        /// 消息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 详细信息
        /// </summary>
        public string Details { get; set; }

        /// <summary>
        /// 异常信息
        /// </summary>
        public string Exception { get; set; }

        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserId { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 客户端IP
        /// </summary>
        public string ClientIp { get; set; }

        /// <summary>
        /// 请求路径
        /// </summary>
        public string RequestPath { get; set; }

        /// <summary>
        /// 请求方法
        /// </summary>
        public string RequestMethod { get; set; }

        /// <summary>
        /// 响应状态码
        /// </summary>
        public int? StatusCode { get; set; }

        /// <summary>
        /// 执行时间（毫秒）
        /// </summary>
        public long ExecutionTimeMs { get; set; }

        /// <summary>
        /// 分类
        /// </summary>
        public string Category { get; set; }

        /// <summary>
        /// 标签
        /// </summary>
        public Dictionary<string, string> Tags { get; set; } = new Dictionary<string, string>();
    }

    /// <summary>
    /// 性能指标
    /// </summary>
    public class PerformanceMetric
    {
        /// <summary>
        /// 指标名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 指标值
        /// </summary>
        public double Value { get; set; }

        /// <summary>
        /// 单位
        /// </summary>
        public string Unit { get; set; }

        /// <summary>
        /// 时间戳
        /// </summary>
        public DateTime Timestamp { get; set; }

        /// <summary>
        /// 标签
        /// </summary>
        public Dictionary<string, string> Tags { get; set; } = new Dictionary<string, string>();
    }

    /// <summary>
    /// 系统状态
    /// </summary>
    public class InternalSystemStatus
    {
        /// <summary>
        /// 系统运行时间
        /// </summary>
        public TimeSpan Uptime { get; set; }

        /// <summary>
        /// CPU使用率
        /// </summary>
        public double CpuUsage { get; set; }

        /// <summary>
        /// 内存使用量
        /// </summary>
        public long MemoryUsed { get; set; }

        /// <summary>
        /// 内存总量
        /// </summary>
        public long MemoryTotal { get; set; }

        /// <summary>
        /// 磁盘使用量
        /// </summary>
        public long DiskUsed { get; set; }

        /// <summary>
        /// 磁盘总量
        /// </summary>
        public long DiskTotal { get; set; }

        /// <summary>
        /// 活跃连接数
        /// </summary>
        public int ActiveConnections { get; set; }

        /// <summary>
        /// 请求数/秒
        /// </summary>
        public double RequestsPerSecond { get; set; }

        /// <summary>
        /// 错误率
        /// </summary>
        public double ErrorRate { get; set; }

        /// <summary>
        /// 最后检查时间
        /// </summary>
        public DateTime LastChecked { get; set; }
    }

    /// <summary>
    /// 健康检查结果
    /// </summary>
    public class InternalHealthCheckResult
    {
        /// <summary>
        /// 检查名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 是否健康
        /// </summary>
        public bool IsHealthy { get; set; }

        /// <summary>
        /// 消息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 持续时间
        /// </summary>
        public TimeSpan Duration { get; set; }

        /// <summary>
        /// 数据
        /// </summary>
        public Dictionary<string, object> Data { get; set; } = new Dictionary<string, object>();

        /// <summary>
        /// 异常
        /// </summary>
        public Exception Exception { get; set; }
    }

    /// <summary>
    /// 监控服务
    /// </summary>
    public interface IMonitoringService
    {
        /// <summary>
        /// 记录日志
        /// </summary>
        Task LogAsync(LogEntry logEntry);

        /// <summary>
        /// 记录性能指标
        /// </summary>
        Task RecordMetricAsync(PerformanceMetric metric);

        /// <summary>
        /// 获取系统状态
        /// </summary>
        Task<InternalSystemStatus> GetSystemStatusAsync();

        /// <summary>
        /// 执行健康检查
        /// </summary>
        Task<List<InternalHealthCheckResult>> PerformHealthChecksAsync();

        /// <summary>
        /// 获取最近的日志
        /// </summary>
        Task<List<LogEntry>> GetRecentLogsAsync(LogLevel level = LogLevel.Information, int count = 100);

        /// <summary>
        /// 获取性能指标历史
        /// </summary>
        Task<List<PerformanceMetric>> GetMetricHistoryAsync(string metricName, DateTime startTime, DateTime endTime);

        /// <summary>
        /// 清理旧日志
        /// </summary>
        Task CleanupOldLogsAsync(DateTime cutoffTime);
    }

    /// <summary>
    /// 监控服务实现
    /// </summary>
    public class MonitoringService : IMonitoringService, ITransientDependency
    {
        private readonly ILogger<MonitoringService> _logger;
        private readonly IClock _clock;

        // 内存存储（实际项目中应该使用数据库或专门的监控系统）
        private static readonly List<LogEntry> _logEntries = new List<LogEntry>();
        private static readonly List<PerformanceMetric> _metrics = new List<PerformanceMetric>();
        private static readonly DateTime _startTime = DateTime.UtcNow;

        public MonitoringService(ILogger<MonitoringService> logger, IClock clock)
        {
            _logger = logger;
            _clock = clock;
        }

        public async Task LogAsync(LogEntry logEntry)
        {
            logEntry.Id = Guid.NewGuid().ToString("N");
            logEntry.Timestamp = _clock.Now;

            _logEntries.Add(logEntry);

            // 保持最近10000条日志
            if (_logEntries.Count > 10000)
            {
                _logEntries.RemoveRange(0, _logEntries.Count - 10000);
            }

            // 同时记录到标准日志
            var microsoftLogLevel = ConvertToMicrosoftLogLevel(logEntry.Level);
            _logger.Log(microsoftLogLevel, logEntry.Message);

            await Task.CompletedTask;
        }

        public async Task RecordMetricAsync(PerformanceMetric metric)
        {
            metric.Timestamp = _clock.Now;

            _metrics.Add(metric);

            // 保持最近5000条指标
            if (_metrics.Count > 5000)
            {
                _metrics.RemoveRange(0, _metrics.Count - 5000);
            }

            await Task.CompletedTask;
        }

        public async Task<InternalSystemStatus> GetSystemStatusAsync()
        {
            var now = _clock.Now;
            var uptime = now - _startTime;

            // 模拟系统状态数据
            var status = new InternalSystemStatus
            {
                Uptime = uptime,
                CpuUsage = new Random().NextDouble() * 100,
                MemoryUsed = new Random().Next(1, 8) * 1024 * 1024 * 1024L, // 1-8GB
                MemoryTotal = 8 * 1024 * 1024 * 1024L, // 8GB
                DiskUsed = new Random().Next(50, 200) * 1024 * 1024 * 1024L, // 50-200GB
                DiskTotal = 500 * 1024 * 1024 * 1024L, // 500GB
                ActiveConnections = new Random().Next(10, 1000),
                RequestsPerSecond = new Random().NextDouble() * 100,
                ErrorRate = new Random().NextDouble() * 5, // 0-5%
                LastChecked = now
            };

            return await Task.FromResult(status);
        }

        public async Task<List<InternalHealthCheckResult>> PerformHealthChecksAsync()
        {
            var healthChecks = new List<InternalHealthCheckResult>();

            // 数据库健康检查
            healthChecks.Add(await CheckDatabaseHealthAsync());

            // MCP服务器健康检查
            healthChecks.Add(await CheckMcpServersHealthAsync());

            // 内存健康检查
            healthChecks.Add(await CheckMemoryHealthAsync());

            // 磁盘健康检查
            healthChecks.Add(await CheckDiskHealthAsync());

            return healthChecks;
        }

        public async Task<List<LogEntry>> GetRecentLogsAsync(LogLevel level = LogLevel.Information, int count = 100)
        {
            var logs = _logEntries
                .Where(l => l.Level >= level)
                .OrderByDescending(l => l.Timestamp)
                .Take(count)
                .ToList();

            return await Task.FromResult(logs);
        }

        public async Task<List<PerformanceMetric>> GetMetricHistoryAsync(string metricName, DateTime startTime, DateTime endTime)
        {
            var metrics = _metrics
                .Where(m => m.Name == metricName && m.Timestamp >= startTime && m.Timestamp <= endTime)
                .OrderBy(m => m.Timestamp)
                .ToList();

            return await Task.FromResult(metrics);
        }

        public async Task CleanupOldLogsAsync(DateTime cutoffTime)
        {
            var removedCount = _logEntries.RemoveAll(l => l.Timestamp < cutoffTime);
            _logger.LogInformation("清理了 {Count} 条旧日志", removedCount);

            await Task.CompletedTask;
        }

        private async Task<InternalHealthCheckResult> CheckDatabaseHealthAsync()
        {
            var startTime = _clock.Now;
            
            try
            {
                // 模拟数据库检查
                await Task.Delay(10);

                return new InternalHealthCheckResult
                {
                    Name = "Database",
                    IsHealthy = true,
                    Message = "数据库连接正常",
                    Duration = _clock.Now - startTime,
                    Data = new Dictionary<string, object>
                    {
                        { "ConnectionTime", 10 },
                        { "Database", "SQL Server" },
                        { "Version", "2019" }
                    }
                };
            }
            catch (Exception ex)
            {
                return new InternalHealthCheckResult
                {
                    Name = "Database",
                    IsHealthy = false,
                    Message = "数据库连接失败",
                    Duration = _clock.Now - startTime,
                    Exception = ex
                };
            }
        }

        private async Task<InternalHealthCheckResult> CheckMcpServersHealthAsync()
        {
            var startTime = _clock.Now;
            
            try
            {
                // 模拟MCP服务器检查
                await Task.Delay(15);

                return new InternalHealthCheckResult
                {
                    Name = "MCP Servers",
                    IsHealthy = true,
                    Message = "MCP服务器运行正常",
                    Duration = _clock.Now - startTime,
                    Data = new Dictionary<string, object>
                    {
                        { "ConnectedServers", 6 },
                        { "TotalServers", 8 },
                        { "ActiveTools", 45 }
                    }
                };
            }
            catch (Exception ex)
            {
                return new InternalHealthCheckResult
                {
                    Name = "MCP Servers",
                    IsHealthy = false,
                    Message = "MCP服务器检查失败",
                    Duration = _clock.Now - startTime,
                    Exception = ex
                };
            }
        }

        private async Task<InternalHealthCheckResult> CheckMemoryHealthAsync()
        {
            var startTime = _clock.Now;
            
            try
            {
                // 模拟内存检查
                await Task.Delay(5);

                var memoryUsage = new Random().NextDouble() * 100;

                return new InternalHealthCheckResult
                {
                    Name = "Memory",
                    IsHealthy = memoryUsage < 90,
                    Message = memoryUsage < 90 ? "内存使用正常" : "内存使用率过高",
                    Duration = _clock.Now - startTime,
                    Data = new Dictionary<string, object>
                    {
                        { "UsagePercent", memoryUsage },
                        { "AvailableMB", 1024 },
                        { "TotalMB", 8192 }
                    }
                };
            }
            catch (Exception ex)
            {
                return new InternalHealthCheckResult
                {
                    Name = "Memory",
                    IsHealthy = false,
                    Message = "内存检查失败",
                    Duration = _clock.Now - startTime,
                    Exception = ex
                };
            }
        }

        private async Task<InternalHealthCheckResult> CheckDiskHealthAsync()
        {
            var startTime = _clock.Now;
            
            try
            {
                // 模拟磁盘检查
                await Task.Delay(8);

                var diskUsage = new Random().NextDouble() * 100;

                return new InternalHealthCheckResult
                {
                    Name = "Disk",
                    IsHealthy = diskUsage < 95,
                    Message = diskUsage < 95 ? "磁盘空间充足" : "磁盘空间不足",
                    Duration = _clock.Now - startTime,
                    Data = new Dictionary<string, object>
                    {
                        { "UsagePercent", diskUsage },
                        { "FreeGB", 50 },
                        { "TotalGB", 500 }
                    }
                };
            }
            catch (Exception ex)
            {
                return new InternalHealthCheckResult
                {
                    Name = "Disk",
                    IsHealthy = false,
                    Message = "磁盘检查失败",
                    Duration = _clock.Now - startTime,
                    Exception = ex
                };
            }
        }

        private Microsoft.Extensions.Logging.LogLevel ConvertToMicrosoftLogLevel(LogLevel level)
        {
            return level switch
            {
                LogLevel.Debug => Microsoft.Extensions.Logging.LogLevel.Debug,
                LogLevel.Information => Microsoft.Extensions.Logging.LogLevel.Information,
                LogLevel.Warning => Microsoft.Extensions.Logging.LogLevel.Warning,
                LogLevel.Error => Microsoft.Extensions.Logging.LogLevel.Error,
                LogLevel.Critical => Microsoft.Extensions.Logging.LogLevel.Critical,
                _ => Microsoft.Extensions.Logging.LogLevel.Information
            };
        }
    }
}